package logic

import (
	"context"
	"errors"
	"furni-manage/furnirpc/furnirpc"
	"furni-manage/furnirpc/internal/svc"
	"furni-manage/model"
	"github.com/zeromicro/go-zero/core/logx"
)

type ManegeAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManegeAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManegeAddLogic {
	return &ManegeAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManegeAddLogic) ManegeAdd(in *furnirpc.ManegeAddRequest) (*furnirpc.ManegeAddResponse, error) {
	// todo: add your logic here and delete this line
	var FindManege model.Manage
	err := FindManege.FindMangeByMangeName(model.DB, in.ManageName)
	begin := model.DB.Begin()
	if err == nil {
		begin.Rollback()
		return nil, errors.New("品牌已存在")
	}
	Logo := model.Logo{
		//Model:    gorm.Model{},
		Name: in.LogoName,
	}

	if err = Logo.FindByLogoName(begin, in.LogoName); err != nil {
		begin.Rollback()
		return nil, errors.New("品牌添加失败")
	}
	class := model.Class{
		//Model:     gorm.Model{},
		Name: in.ClassName,
	}

	if err = class.FindByClassName(begin, in.ClassName); err != nil {
		begin.Rollback()
		return nil, errors.New("分类添加失败")
	}
	Manage := model.Manage{
		//Model:       gorm.Model{},
		ManageName:  in.ManageName,
		LogoId:      int(Logo.ID),
		ManageNum:   int(in.ManageNum),
		ManagePrice: float64(in.ManagePrice),
		ClassId:     int(class.ID),
	}

	if err = Manage.ManageAdd(begin); err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()
	return &furnirpc.ManegeAddResponse{
		ManageId: int64(Manage.ID),
	}, nil
}
